using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Domain.Entities;
using Domain.Enums;
using Domain.UserManagenent;

namespace Logic.ResultManagement
{
    public class ResultExporter: IExporter
    {
        public Stream Export(IEnumerable<IEntity> entities)
        {
            if (entities.Count() > 0 && entities.GetEnumerator().Current.GetType().Equals(typeof(Quiz)))
            {
                var tempXmlStructure = new XmlDocument();
                foreach(Quiz quiz in entities)
                {
                    if (quiz.User == null || quiz.Chapter == null || quiz.Chapter.Topic == null || quiz.Chapter.Topic.Course == null || quiz.Questions == null)
                        continue;
                    var userNode = AddOrSelect(tempXmlStructure, "user", quiz.User.UserName);
                    var courseNode = AddOrSelect(userNode, "course", quiz.Chapter.Topic.Course.CourseName);
                    var topicNode = AddOrSelect(courseNode, "topic", quiz.Chapter.Topic.TopicName);
                    var chapter = AddOrSelect(topicNode, "chapter", quiz.Chapter.ChapterName);

                    if (chapter.Attributes["attempts"] == null)
                        chapter.Attributes.Append(tempXmlStructure.CreateAttribute("attempts")).Value = "0";
                    chapter.Attributes["attempts"].Value = (int.Parse(chapter.Attributes["attempts"].Value) + 1).ToString();
                    
                    if (chapter.Attributes["status"] == null)
                        chapter.Attributes.Append(tempXmlStructure.CreateAttribute("status")).Value = "false";

                    var passed = true;
                    foreach (var question in quiz.Questions)
                    {
                        passed &= question.QuestionStatus != QuestionStatus.Right;
                        if (passed == false)
                            break;
                    }
                    chapter.Attributes["status"].Value = (bool.Parse(chapter.Attributes["status"].Value) || passed).ToString();
                }
                return WriteXmlToStream(tempXmlStructure);
            }
            return null;
        }

        private Stream WriteXmlToStream(XmlDocument xmlDoc)
        {
            throw new NotImplementedException();
        }

        private XmlNode AddOrSelect(XmlNode to, string entityType, string entityName)
        {
            var searchNode = to.SelectSingleNode(entityType + "[name = " + entityName + "]");
            if (searchNode == null)
            {
                searchNode = to.OwnerDocument.CreateNode(entityType, entityName, "");
                to.AppendChild(searchNode);
            }
            return searchNode;
        }
    }
}